/* 
 * File:   main.cpp
 * Author: Vicky.H
 * Email:  eclipser@163.com
 */
#include <iostream>
#include <time.h>
#include "Thread.h"
#include "Lock.h"

class MyThread : public Thread {
public:
    void run() {
        for(;;) {
            sleep(1);
            std::cout << "thread 1" << time(0) << std::endl;
        }
    }
};

class MyThread2 : public Thread {
public:
    void run() {
        for(;;) {
            sleep(5);
            std::cout << "thread 2" << time(0) << std::endl;
        }
    }
};

class MyThread3 : public Thread {
public:
    void run() {
        std::cout << "thread 3" << time(0) << std::endl;
    }
};

class MyThread4 : public Thread {
public:
    MyThread4() : isAlive (false) {
    }
    
    void start() {
        lock.Lock();
        if (!isAlive)
            isAlive = true;
        lock.Unlock();
        Thread::start();
    }
    
    void stop() {
        lock.Lock();
        if (isAlive)
            isAlive = false;
        lock.Unlock();
    }
    
    void run() {
        bool _isAlive;
        lock.Lock();
        _isAlive = isAlive;
        lock.Unlock();
        
        while(_isAlive) {
            sleep(1);
            std::cout << "thread 4" << time(0) << std::endl;
            
            lock.Lock();
            _isAlive = isAlive;
            lock.Unlock();
        }
    }
private:
    bool isAlive;
    MyLock lock;
};

/*
 * 
 */
int main(void) {

//    MyThread myThread;
//    myThread.start();
//    
//    sleep(2);
//    
//    std::cout << "main thread!" << std::endl;
//    std::cout << g_QuitThreadCount << std::endl;
//    
//    sleep(2);
//    
//    MyThread2 myThread2;
//    myThread2.start();
//    
//    sleep(1);
//    std::cout << "main thread!" << std::endl;
//    std::cout << g_QuitThreadCount << std::endl;
//    
//    MyThread3 myThread3;
//    myThread3.start();
//    
//    sleep(1);
//    std::cout << g_QuitThreadCount << std::endl;
    
    MyThread4 myThread4;
    myThread4.start();
    
    sleep(10);
    std::cout << "myThread4 stop !" << std::endl;
    myThread4.stop();
    
    // 保持父线程运行
    sleep(100);
    return 0;
}
